package com.ykt.service;

import com.jfinal.aop.Enhancer;
import com.ykt.common.thirdapi.ys7.Ys7ApiHelper;
import com.ykt.common.thirdapi.ys7.model.Ys7Camera;
import com.ykt.model.Camera;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**
 * 萤石云视频api操作，本类一部分方法将移入CMS中
 * @author long.hua
 * @version 1.0.0
 * @since 2015-12-22 00:27
 */
public class Ys7Service {
    private static final Logger LOGGER = LoggerFactory.getLogger(Ys7Service.class);

    private Camera cameraDao = Camera.dao;

    private Ys7ApiHelper ys7ApiHelper = Enhancer.enhance(Ys7ApiHelper.class.getName(), Ys7ApiHelper.class);


    /**
     * 循环获取设备列表，保存到数据库
     */
    public void syncCamera(){
        int offset = 0; // 0表示第一页
        int PAGE_SIZE = 100;

        while(true){
            String token = ys7ApiHelper.getAccessToken(); // 保证token前后一致

            List<Ys7Camera> list = ys7ApiHelper.getCameraList(offset, PAGE_SIZE, token);
            if(list == null || list.isEmpty()){
                break;
            }

            saveCameraList(list);

            offset += PAGE_SIZE;
        }

    }

    private void saveCameraList(List<Ys7Camera> cameraVos){
        for (Ys7Camera cameraVo : cameraVos) {
            Camera entity  = cameraDao.findByDeviceId(cameraVo.getDeviceId());

            boolean notExist = (entity == null);
            if(notExist) {
                entity = new Camera();
            }

            entity.set(Camera.device_id, cameraVo.getDeviceId());
            entity.set(Camera.device_serial, cameraVo.getDeviceSerial());
            entity.set(Camera.device_name, cameraVo.getDeviceName());
            entity.set(Camera.camera_id, cameraVo.getCameraId());
            entity.set(Camera.camera_no, cameraVo.getCameraNo());
            entity.set(Camera.camera_name, cameraVo.getCameraName());
            entity.set(Camera.status, cameraVo.getStatus());
            entity.set(Camera.is_shared, cameraVo.getIsShared());
            //entity.set(Camera.picUrl, cameraVo.getPicUrl());
            entity.set(Camera.is_encrypt, cameraVo.getIsEncrypt());
            entity.set(Camera.defence, cameraVo.getDefence());

            if(notExist) {
                entity.save();
            } else {
                entity.update();
            }
        }
    }

    public static void main(String[] args) {
        new Ys7Service().syncCamera();
    }
}

